<template>
  <div class="call-table" style="overflow: hidden" id="callTable">
    <div class="treeDrag">
      <div class="treeHeader">
        <div class="label-checkbox"></div>
        <div>{{$t('config.channel.labelName')}}</div>
        <div>{{$t('config.channel.status')}}</div>
        <div>{{$t('public.operate')}}</div>
      </div>
      <draggable :list="data" forceFallback  handle='.drag' style='box-sizing:border-box' @change = 'draggChange'>
        <div class="firstLevel" v-for="(item, index) in data" :key="item._id">
            <div class="leverFirst list_box" v-show="getEnableState(item)">
              <label class="el-checkbox label-checkbox" :class="checkArr.indexOf(item._id+'_'+item.level) > -1?'is-checked':''" >
                <span class="el-checkbox__input" :class="checkArr.indexOf(item._id+'_'+item.level) > -1?'is-checked':''" >
                  <span class="el-checkbox__inner" @click.stop="changeCheckbox(item)"></span>
                </span>
              </label>
              <div>
                <span class='drag'><i class="iconfont icon-shunxutuozhuai"></i></span>
                <span @click.stop="treeShowLabel(index, item)" class="operate">
                  <i v-if="!item.flag && item.level !== 5" class="icon iconfont icon-zhankai"></i>
                  <i v-if="item.flag && item.level !== 5" class="icon iconfont icon-zuixiaohua"></i>
                </span>
                <span v-if="item.status && item._id" :class = "{is_error: item.stopSave==true}">
                  <el-input v-focus
                    v-model.trim="item.name"
                    class="label-input"
                    @blur = "boxBlur1(item)"></el-input>
                </span>
                <span v-if='!item.status' class="name-box">{{item.name}}</span>
                <span v-show="item.status && !item._id" :class = "{is_error: item.stopSave==true}">
                  <el-input v-model.trim="item.name"
                            class="label-input"></el-input>
                  <div style="display: inline-block">
                    <span class="delete" @click.stop="handleTreeChannel(index, data)">
                        <i class="el-icon-close"></i>
                    </span>
                  </div>
                </span>
              </div>
              <div><p><span v-show="item.enable === true">{{$t('config.channel.enabled')}}</span><span v-show="item.enable === false" :class = "{is_stop: item.enable==false}">{{$t('config.channel.disabled')}}</span></p></div>
              <div>
                <div v-show="item.name" class="operate-btn">
                  <span @click="handleTreeEdit(index, item)" class="padding-r-10 cursor">{{$t('public.edit')}}</span>
                  <span @click="handleAddLabeltest(index, item)" class="padding-r-10 cursor">{{$t('config.channel.addTwoLabel')}}</span>
                  <span @click="handleDisabled(index, item, data)">
                    <span v-show="item.enable === false" class="cursor">{{$t('config.channel.enabled')}}</span>
                    <span v-show="item.enable === true" class="cursor" :class = "{is_stopBtn: item.enable==true}">{{$t('config.channel.disabled')}}</span>
                  </span>
                </div>
              </div>
            </div>
          <draggable :list="item.child" forceFallback  handle='.drag'  class = 'treeChild' :ref="item.keyStr">
            <div class="SecondLevel treeChild" v-for="(it, index) in item.child" :key="it._id" v-if="item.flag">
              <div class="leverSecond list_box" v-show="getEnableState(it, item)">
                <label class="el-checkbox label-checkbox" :class="checkArr.indexOf(it._id+'_'+it.level) > -1?'is-checked':''" >
                  <span class="el-checkbox__input" :class="checkArr.indexOf(it._id+'_'+it.level) > -1?'is-checked':''">
                    <span class="el-checkbox__inner" @click.stop="changeCheckbox(it)"></span>
                  </span>
                </label>
                <div>
                  <!-- <span class='drag'><i class="iconfont icon-shunxutuozhuai"></i></span> -->
                  <span @click.stop="treeShowLabel(index, it)" class="operate paddelvel2">
                    <i v-if="!it.flag && it.level !== 5" class="icon iconfont icon-zhankai"></i>
                    <i v-if="it.flag && it.level !== 5" class="icon iconfont icon-zuixiaohua"></i>
                  </span>
                  <span v-if="it.status && it._id" :class = "{is_error: it.stopSave==true}">
                    <el-input v-focus
                      v-model.trim="it.name"
                      class="label-input"
                      @blur = "boxBlur1(it)"></el-input>
                  </span>
                  <span v-if='!it.status' class="name-box">{{it.name}}</span>
                  <span v-show="it.status && !it._id" :class = "{is_error: item.stopSave==true}">
                    <el-input v-model.trim="it.name"
                              class="label-input"></el-input>
                    <div style="display: inline-block">
                      <span class="delete" @click.stop="handleTreeChannel(index, item)">
                          <i class="el-icon-close"></i>
                      </span>
                    </div>
                  </span>
                </div>
                <div><p><span v-show="it.enable === true">{{$t('config.channel.enabled')}}</span><span v-show="it.enable === false" :class = "{is_stop: it.enable==false}">{{$t('config.channel.disabled')}}</span></p></div>
                <div>
                  <div v-show="it.name" class="operate-btn">
                    <span @click.stop="handleTreeEdit(index, it)" class="padding-r-10 cursor">{{$t('public.edit')}}</span>
                    <span @click.stop="handleAddLabeltest(index, it)" class="padding-r-10 cursor">{{$t('config.channel.addThreeLabel')}}</span>
                    <span @click.stop="handleDisabled(index, it, item)"><span v-show="it.enable === false" class="cursor">{{$t('config.channel.enabled')}}</span><span v-show="it.enable === true" class="cursor" :class = "{is_stopBtn: it.enable==true}">{{$t('config.channel.disabled')}}</span></span>
                  </div>
                </div>
              </div>
              <draggable :list="it.child" forceFallback  handle='.drag'  :ref="it.keyStr" class = 'treeChild'>
                  <div class="ThirdLevel" v-for="(ele, index) in it.child" :key="ele._id" v-if="it.flag">
                    <div class="leverThird list_box" v-show="getEnableState(ele, item)">
                     <label class="el-checkbox label-checkbox" :class="checkArr.indexOf(ele._id+'_'+ele.level) > -1?'is-checked':''" >
                        <span class="el-checkbox__input" :class="checkArr.indexOf(ele._id+'_'+ele.level) > -1?'is-checked':''">
                          <span class="el-checkbox__inner" @click.stop="changeCheckbox(ele)" ></span>
                         </span>
                      </label>
                      <div>
                        <!-- <span class='drag'><i class="iconfont icon-shunxutuozhuai"></i></span> -->
                        <span @click.stop="treeShowLabel(index, ele)" class="operate paddelvel3">
                             <i v-if="!ele.flag && ele.level !== 5" class="icon iconfont icon-zhankai"></i>
                             <i v-if="ele.flag && ele.level !== 5" class="icon iconfont icon-zuixiaohua"></i>
                        </span>
                        <span v-if="ele.status && ele._id" :class = "{is_error: ele.stopSave==true}">
                          <el-input v-focus
                            v-model.trim="ele.name"
                            class="label-input"
                            @blur = "boxBlur1(ele)"></el-input>
                        </span>
                        <span v-if='!ele.status' class="name-box">{{ele.name}}</span>
                        <span v-show="ele.status && !ele._id" :class = "{is_error: ele.stopSave==true}">
                          <el-input v-model.trim="ele.name"
                                    class="label-input"></el-input>
                          <div style="display: inline-block">
                            <span class="delete" @click.stop="handleTreeChannel(index, it)">
                                <i class="el-icon-close"></i>
                            </span>
                          </div>
                        </span>
                      </div>
                      <div><p><span v-show="ele.enable === true">{{$t('config.channel.enabled')}}</span><span v-show="ele.enable === false" :class = "{is_stop: ele.enable==false}">{{$t('config.channel.disabled')}}</span></p></div>
                      <div>
                        <div v-show="ele.name" class="operate-btn">
                          <span @click.stop="handleTreeEdit(index, ele)" class="padding-r-10 cursor">{{$t('public.edit')}}</span>
                          <span @click.stop="handleAddLabeltest(index, ele)" class="padding-r-10 cursor">{{$t('config.channel.addFourthLabel')}}</span>
                          <span @click.stop="handleDisabled(index, ele, it)"><span v-show="ele.enable === false" class="cursor">{{$t('config.channel.enabled')}}</span><span v-show="ele.enable === true" class="cursor" :class = "{is_stopBtn: ele.enable==true}">{{$t('config.channel.disabled')}}</span></span>
                        </div>
                      </div>
                    </div>
                    <draggable :list="ele.child" forceFallback  handle='.drag'  :ref="ele.keyStr" class = 'treeChild'>
                      <div class="FourthLevel" v-for="(fourth, index) in ele.child" :key="fourth._id"  v-if="ele.flag">
                        <div class="leverFourth list_box" v-show="getEnableState(fourth, item)">
                          <label class="el-checkbox label-checkbox" :class="checkArr.indexOf(fourth._id+'_'+fourth.level) > -1?'is-checked':''">
                            <span class="el-checkbox__input" :class="checkArr.indexOf(fourth._id+'_'+fourth.level) > -1?'is-checked':''">
                              <span class="el-checkbox__inner" @click.stop="changeCheckbox(fourth)" ></span>
                            </span>
                          </label>
                          <div>
                            <!-- <span class='drag'><i class="iconfont icon-shunxutuozhuai"></i></span> -->
                            <span @click.stop="treeShowLabel(index, fourth)" class="operate paddelvel4">
                                  <i v-if="!fourth.flag && fourth.level !== 5" class="icon iconfont icon-zhankai"></i>
                                  <i v-if="fourth.flag && fourth.level !== 5" class="icon iconfont icon-zuixiaohua"></i>
                            </span>
                            <span v-if="fourth.status && fourth._id" :class = "{is_error: fourth.stopSave==true}">
                              <el-input v-focus
                                        v-model.trim="fourth.name"
                                        class="label-input"
                                        @blur = "boxBlur1(fourth)"></el-input>
                            </span>
                            <span v-if='!fourth.status' class="name-box">{{fourth.name}}</span>
                            <span v-show="fourth.status && !fourth._id" :class = "{is_error: fourth.stopSave==true}">
                             <el-input v-model.trim="fourth.name"
                                    class="label-input"></el-input>
                              <div style="display: inline-block">
                                <span class="delete" @click.stop="handleTreeChannel(index, ele)">
                                    <i class="el-icon-close"></i>
                                </span>
                              </div>
                             </span>
                          </div>
                          <div><p><span v-show="fourth.enable === true">{{$t('config.channel.enabled')}}</span><span v-show="fourth.enable === false" :class = "{is_stop: fourth.enable==false}">{{$t('config.channel.disabled')}}</span></p></div>
                          <div>
                            <div v-show="fourth.name" class="operate-btn">
                              <span @click.stop="handleTreeEdit(index, fourth)" class="padding-r-10 cursor">{{$t('public.edit')}}</span>
                              <span @click.stop="handleAddLabeltest(index, fourth)" class="padding-r-10 cursor">{{$t('config.channel.addFifthLabel')}}</span>
                              <span @click.stop="handleDisabled(index, fourth, ele)"><span v-show="fourth.enable === false" class="cursor">{{$t('config.channel.enabled')}}</span><span v-show="fourth.enable === true" class="cursor" :class = "{is_stopBtn: fourth.enable==true}">{{$t('config.channel.disabled')}}</span></span>
                            </div>
                          </div>
                        </div>
                        <draggable :list="fourth.child"  forceFallback  handle='.drag'  :ref="fourth.keyStr" class = 'treeChild'>
                          <div class="FifthLevel" v-for="(fifth, index) in fourth.child" :key="fifth._id" v-if="fourth.flag">
                            <div class="leverFifth list_box" v-show="getEnableState(fifth, item)">
                              <label class="el-checkbox label-checkbox" :class="checkArr.indexOf(fifth._id+'_'+fifth.level) > -1?'is-checked':''" >
                                <span class="el-checkbox__input" :class="checkArr.indexOf(fifth._id+'_'+fifth.level) > -1?'is-checked':''">
                                 <span class="el-checkbox__inner" @click.stop="changeCheckbox(fifth)"></span>
                                 </span>
                              </label>
                              <div>
                                <!-- <span class='drag'><i class="iconfont icon-shunxutuozhuai"></i></span> -->
                                <span @click.stop="treeShowLabel(index, fifth)" class="operate paddelvel5"></span>
                                <span v-if="fifth.status && fifth._id" :class = "{is_error: fifth.stopSave==true}">
                                  <el-input v-focus
                                            v-model.trim="fifth.name"
                                            class="label-input"
                                            @blur = "boxBlur1(fifth)"></el-input>
                                </span>
                                <span v-if='!fifth.status' class="name-box">{{fifth.name}}</span>
                                <span v-show="fifth.status && !fifth._id" :class = "{is_error: fifth.stopSave==true}">
                                  <el-input v-model.trim="fifth.name"
                                                  class="label-input"></el-input>
                                  <div style="display: inline-block">
                                    <span class="delete" @click.stop="handleTreeChannel(index, fourth)">
                                        <i class="el-icon-close"></i>
                                    </span>
                                  </div>
                                </span>
                              </div>
                              <div><p><span v-show="fifth.enable === true">{{$t('config.channel.enabled')}}</span><span v-show="fifth.enable === false" :class = "{is_stop: fifth.enable==false}">{{$t('config.channel.disabled')}}</span></p></div>
                              <div>
                                <div v-show="fifth.name" class="operate-btn">
                                  <span @click.stop="handleTreeEdit(index, fifth)" class="padding-r-10 cursor">{{$t('public.edit')}}</span>
                                  <span @click.stop="handleDisabled(index, fifth, fourth)"><span v-show="fifth.enable === false" class="cursor">{{$t('config.channel.enabled')}}</span><span v-show="fifth.enable === true" class="cursor" :class = "{is_stopBtn: fifth.enable==true}">{{$t('config.channel.disabled')}}</span></span>
                                </div>
                              </div>
                            </div>
                          </div>
                        </draggable>
                      </div>
                    </draggable>
                  </div>
                </draggable>
            </div>
          </draggable>
      </div>
    </draggable>
  </div>
  <div class="label-batch" v-if="checkArr.length > 0">
    <el-checkbox v-model.trim="allChecked" style="margin-right:30px;" @change="checkAll">{{$t('public.checkAll')}}</el-checkbox>
    <span v-show="filterEnable !== 'open'" @click="batchEnableOrDisabled(true)"><i class="iconfont icon-piliangqiyong"></i>批量启用</span>
    <span v-show="filterEnable !== 'close'" @click="batchEnableOrDisabled(false)"><i class="iconfont icon-piliangtingyong"></i>批量停用</span>
    <div class="count">{{$t('public.already')}}<b>{{ checkArr.length || 0 }}</b>{{$t('public.term')}} <i class="el-icon-close"  @click="restAllChecked"></i></div>
  </div>
  </div>
</template>
<script>
  import Vue from 'vue'
  import draggable from 'vuedraggable'
  export default {
    name: 'treeTable',
    data () {
      return {
        allChecked: false,
        saveFlag: false,
        checkArr: [],
        labelList: [],
        maxLevel: 0,
        stopAddFlag: false,
        addBorderFlag: false,
        data: [],
        dragFlagState: false
      }
    },
    components: { draggable },
    props: ['tableData', 'filterEnable', 'vagueStr'],
    directives: {
      focus: {
        inserted: function (el) {
          el.getElementsByClassName('el-input__inner')[0].focus()
        }
      }
    },
    methods: {
      boxBlur1 (data) {
        if (data.name === '') {
          data.stopSave = true
          return
        }
        data.status = false
      },
//      展开
      unfolded (index, row) {
        this.labelList.forEach((label) => {
          let a = label.keyStr.split('-')
          let str = ''
          for (let i = 0; i < row.level; i++) {
            str += a[i] + '-'
          }
          if (label.keyStr.length > row.keyStr.length && (str.substring(0, str.length - 1) === row.keyStr) && label.level === row.level + 1) {
            document.getElementsByClassName(label.keyStr)[0].style.display = 'table-row'
          }
        })
        row.flag = true
      },
//      收起
      folded (index, row) {
        // 收起下级
        this.labelList.forEach((label) => {
          let a = label.keyStr.split('-')
          let str = ''
          for (let i = 0; i < row.level; i++) {
            str += a[i] + '-'
          }
          if (label.keyStr.length > row.keyStr.length && (str.substring(0, str.length - 1) === row.keyStr)) {
            if (label.level === row.level + 1 && label.level < this.maxLevel) {
              label.flag = false
            }
            document.getElementsByClassName(label.keyStr)[0].style.display = 'none'
          }
        })
        row.flag = false
      },
//      数组转化
      transform (arr) {
        const newArr = JSON.parse(JSON.stringify(arr))
//        const newArr = [...arr]
        const cache = {}
        newArr.forEach(item => {
          !item.stopSave && delete item.stopSave
          if (item.status === false || item.status === true) {
            delete item.status
          }
          if (item.flag === false || item.flag === true) {
            delete item.flag
          }
          cache[item.keyStr] = item
          item.child = []
        })
        return newArr.map(item => {
          !item.stopSave && delete item.stopSave
          if (item.status === false || item.status === true) {
            delete item.status
          }
          if (item.flag === false || item.flag === true) {
            delete item.flag
          }
          let fatherKey = item.keyStr.split('-')
          if (fatherKey.length > 1) {
            fatherKey.pop()
          }
          fatherKey = fatherKey.join('-')
          if (/^child_\d+$/.test(item.keyStr)) {
            return item
          } else {
            if (!cache[fatherKey]) {
              console.error('无父节点')
            }
            cache[fatherKey].child.push(item)
          }
        }).filter(x => x)
      },
      isRepeat (arr) {
        let hash = {}
        for (let i in arr) {
          if (hash[arr[i].name]) {
            let name = arr[i].name
            if (arr[0].level === 1) {
              return name
            } else {
              let array = arr.filter((item) => {
                return (item.name === name)
              })
              let keyStrArr = []
              array.forEach((item2) => {
                let keyStr = item2.keyStr
                let cutKeyStr = arr[0].level === 2 ? keyStr.substring(0, keyStr.indexOf('-')) : keyStr.substring(0, keyStr.indexOf('-', keyStr.indexOf('-') + 1))
                if (keyStrArr.indexOf(cutKeyStr) === -1) {
                  keyStrArr.push(cutKeyStr)
                }
              })
              if (keyStrArr.length !== 0) {
                if (keyStrArr.length < array.length) {
                  return name
                }
              }
            }
          }
          hash[arr[i].name] = true
        }
        return false
      },
  //      保存标签
      handlesaveLabel () {
        if (this.labelList.length === 0) {
          this.$message.error(this.$t('channelsettings.callLabel5'))
          return
        }
        this.saveFlag = false
        this.labelList.forEach((item) => {
          if (item.name === '') {
            console.log(item)
            item.stopSave = true
            this.saveFlag = true
          } else {
            item.stopSave = false
          }
        })
        if (this.saveFlag) {
          this.$message.error(this.$t('config.channel.notEmptyLable'))
          return
        }
        let repeatFlag = false
        let repData = ''
        for (let i = 1; i <= this.maxLevel; i++) {
          let arr1 = []
          arr1 = this.labelList.filter(item => {
            return (item.level === i)
          })
          const repeatData = this.isRepeat(arr1)
          if (repeatData) {
            repData = repeatData
            repeatFlag = true
          }
        }
        if (repeatFlag) {
          this.$message.error(this.$t('channelsettings.callLabel6', {repeat: repData}))
          return
        }
        this.$store.dispatch('saveMultiCallLabels', this.transform(this.labelList)).then((resp) => {
          console.log(resp)
          if (resp.success) {
            this.$emit('refreshData')
          }
        })
      },
      handlesaveTreeLabel () {
        let str = this.recursiveVerification(this.data)
        if (str === 'null') {
          this.$message.error(this.$t('channelsettings.callLabel5'))
          return
        } else if (str === 'repeat') {
          return
        }
        this.$store.dispatch('saveMultiCallLabels', this.data).then((resp) => {
          if (resp.success) {
            this.$message.success(this.$t('monitor.saveSuccess'))
            this.$emit('refreshData')
          }
        })
      },
//      取消操作
      handleChannel (index, row) {
        this.$confirm(this.$t('channelsettings.callLabel1'), this.$t('public.tip'), {
          confirmButtonText: this.$t('public.confirm'),
          cancelButtonText: this.$t('public.cancel'),
          cancelButtonClass: 'primary_btn',
          confirmButtonClass: 'primary_btn',
          type: 'warning'
        }).then(() => {
          this.labelList.forEach((item, index1) => {
            if (item.keyStr.length > row.keyStr.length && item.keyStr.indexOf(row.keyStr) !== -1) {
              this.labelList.splice(index1, 1)
              this.labelList.length--
            }
          })
          this.labelList.splice(index, 1)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: this.$t('public.cancel')
          })
        })
      },
      rowClassName ({row, index}) {
        return '' + row.keyStr
      },
//      通过keyStr添加唯一的className
      className (row, index) {
        return '' + row.keyStr
      },
//      展开／收起操作
      showLabel (index, row) {
        let flag = false
        if (row.flag) {
          this.labelList.forEach((item) => {
            if (item._id === '' || item.status === true) {
              if (row.keyStr.split('-').length < item.keyStr.split('-').length) {
                let _data = item.keyStr.substring(0, item.keyStr.lastIndexOf('-'))
                if (_data.indexOf(row.keyStr) !== -1) {
                  flag = true
                }
              }
            }
          })
          if (flag) {
            return
          }
          this.folded(index, row)
        } else {
          this.unfolded(index, row)
        }
      },
//      编辑标签
      handleEdit (index, row) {
        row.status = true
      },
      parentStopStatus (row, p) {
        let par = {}
        if (row.level !== 1) {
          this.labelList.forEach((item) => {
            if (item.keyStr === (row.keyStr.substring(0, row.keyStr.lastIndexOf('-')))) {
              par = item
            }
          })
          p.push(par)
          this.parentStopStatus(par, p)
        }
      },
//      停用
      handleDisabled (index, row, parentArr) {
        this.draggChange()
        row.enable = !row.enable
        this.setTreeEnable(row, row.enable)
        if (parentArr.child) {
          parentArr.child.splice(index, 1)
          if (!row.enable) {
            parentArr.child.push(row)
          } else {
            parentArr.child.unshift(row)
          }
        } else {
          parentArr.splice(index, 1)
          if (!row.enable) {
            parentArr.push(row)
          } else {
            parentArr.unshift(row)
          }
        }
        // this.$emit('filterEnableUpdate', 'all')
      },
    setTreeEnable (data, enable) {
       if (data.child) {
         data.child.forEach((item, index) => {
           item.enable = enable
           this.setTreeEnable(item, enable)
         })
       }
    },
    treeShowLabel (index, item, isOpen) {
      if (this.$refs[item.keyStr][0] && !isOpen) {
        this.$refs[item.keyStr][0].$el.style.display === 'none' || !this.$refs[item.keyStr][0].$el.style.display ? this.$refs[item.keyStr][0].$el.style.display = 'block' : this.$refs[item.keyStr][0].$el.style.display = 'none'
        if (this.$refs[item.keyStr][0].$el.style.display === 'block') {
          this.$set(item, 'flag', true)
        } else {
          this.$set(item, 'flag', false)
        }

      }
      if (isOpen) {
        this.$refs[item.keyStr][0].$el.style.display = 'block'
        this.$set(item, 'flag', true)
      }
    },
     handleAddLabeltest (index, item) {
        if (item) {
          let str = item.keyStr + '-' + (item.child.length + 1)
          item.child.push({
              child: [],
              keyStr: str,
              level: item.level + 1,
              name: '',
              _id: '',
              type: '',
              enable: true,
              status: true,
              flag: false,
              stopSave: false
            })
          this.treeShowLabel(index, item, true)
        } else {
          if(this.data.length >= 50) {
            this.$message.error(this.$t('channelsettings.callLabel2'))
            return
          }
          let str = 'child_' + (this.data.length + 1)
          this.data.push({
            keyStr: str,
            level: 1,
            name: '',
            type: 'multi',
            enable: true,
            id: '',
            child: [],
            status: true,
            flag: false,
            stopSave: false
          })
        }
        this.$emit('emptyStr')
        this.$emit('filterEnableUpdate', 'all')
      },
      handleTreeEdit (index, item) {
        this.$emit('emptyStr')
        item.status = true
        // this.$set(item, 'status', true)
      },
      handleTreeChannel (index, item) {
        this.$confirm(this.$t('channelsettings.callLabel1'), this.$t('public.tip'), {
          confirmButtonText: this.$t('public.confirm'),
          cancelButtonText: this.$t('public.cancel'),
          cancelButtonClass: 'primary_btn',
          confirmButtonClass: 'primary_btn',
          type: 'warning'
        }).then(() => {
          if (item.child) {
            item.child.splice(index, 1)
          } else {
            item.splice(index, 1)
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: this.$t('public.cancel')
          })
        })
      },
      getEnableState (item, fItem) {
        let strBoolean = false
        let str = this.vagueStr
        if (!this.vagueStr) {
          strBoolean = true
        } else {
          if (this.vagueStr && this.getRecursiveState(item, str)) {
            strBoolean = true
          } else {
            strBoolean = false
          }
        }
        if (this.filterEnable === 'open') {
          if (item.level !== 1) {
            return fItem.enable && item.enable && strBoolean
          } else {
            return item.enable && strBoolean
          }
        } else if (this.filterEnable === 'close') {
          if (item.level !== 1) {
            return !fItem.enable && strBoolean
          } else {
             return !item.enable && strBoolean
          }
        } else {
          return strBoolean
        }
      },
      changeCheckbox (data, parent) { // 递归处理，父级选中或取消选中的时候，子级也跟着操作
        const checkIndex = this.checkArr.indexOf(`${data._id}_${data.level}`)
        if (checkIndex < 0) { // 已选中的数组里没有匹配到，push
          if (!parent || this.checkArr.indexOf(`${parent._id}_${parent.level}`) >= 0) { // 不是父级选中带动选中，即自己操作的zi
            this.checkArr.push(`${data._id}_${data.level}`)
          }
        } else { // 有匹配到，splice
          if (!parent || this.checkArr.indexOf(`${parent._id}_${parent.level}`) < 0) { // 不是父级选中带动选中，即自己操作的zi
            this.checkArr.splice(checkIndex, 1)
          }
        }
        if (data.child && data.child.length > 0) {
          data.child.forEach(item => {
            if (item.child && item.child.length > 0) { // 如果还有孩子，递归处理
              this.changeCheckbox(item, data)
            } else { // 没有孩子了，处理当前层级的选中状态
              const itemIndex = this.checkArr.indexOf(`${item._id}_${item.level}`)
              if (this.checkArr.indexOf(`${data._id}_${data.level}`) > -1) { // 父级有选中，子级全部选中
                this.checkArr.push(`${item._id}_${item.level}`)
              } else {
                if (itemIndex > -1) {
                  this.checkArr.splice(itemIndex, 1)
                }
              }
            }
          })
        }
      },
      checkAll (checked) {
        if (checked) {
          this.checkArr = [] // 全选的时候，先把之前选中的置空，重新选择
          this.data.forEach(item => {
            if (this.getEnableState(item)) { // 先匹配出一级可见的
              this.changeCheckbox(item) // 触发递归，选中所有孩子
            }
          })
        } else {
          this.restAllChecked()
        }
      },
      restAllChecked () { // 把所有选中的重置成未选中
        this.allChecked = false
        this.checkArr = []
      },
      batchEnableOrDisabled (enabled) {
        this.$store.dispatch('batchUpdateCallLabelStatus', {ids: this.checkArr, enabled}).then((resp) => {
          if (resp && resp.success) {
            this.restAllChecked()
            this.$emit('refreshData')
          }
        })
      },
      getRecursiveState (item, str) {
        if (item.name.indexOf(str) > -1){
           return true
          } else {
           if (item.child) {
            for (let i = 0; i < item.child.length; i++) {
              if ( item.child[i].name.indexOf(str) > -1) {
                return true
              } else {
                return this.getEnableState(item.child[i], str)
              }
            }
          }
          return false
        }
      },
      forceUpdate () {
        this.$forceUpdate()
      },
      recursiveVerification (data) {
        try {
          let repeat = this.isRepeat(data)
          if (repeat) {
            this.$message.error(this.$t('channelsettings.callLabel6', {repeat: repeat}))
            throw 'repeat'
          }
          data.forEach((item, index) => {
           if (!item.name) {
             // this.$message.error(this.$t('channelsettings.callLabel5'))
             console.log(item, '查出空的item')
             throw 'null'
           } else {
             item.status = false
             item.flag = false
             if (item.level === 1) {
              if (this.dragFlagState) {
                item.sort = (index + 1)
              }
             }
             if (this.dragFlagState) {
               item.dragFlag = true
             }
           }
           if (item.child) {
             let str = this.recursiveVerification(item.child)
             if(str==='null' || str==='repeat') {
               throw str
             }
           }
         })
          return true
        } catch (error) {
          return error
        }
      },
      draggChange (evt, evt1) {
        this.dragFlagState = true
      }
    },
    beforeMount () {
      this.data = this.tableData
    },
    watch: {
      filterEnable (value, oldVal) {
        this.restAllChecked()
        this.forceUpdate()
      }
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../../assets/common.styl"
  .name-box
    overflow: hidden
    text-overflow:ellipsis
    white-space: nowrap
  .treeHeader
    border 1px solid #e7e7eb
    border-bottom 0px
    border-right 0px
    display flex
    background #f4f5f9
    box-sizing border-box
    font-weight bold
  .treeHeader > div
    box-sizing border-box
    border-right 1px solid #e7e7eb
    padding 10px
    width 33.333333333%
  .operate
    padding 0 5px 0
  .drag
    cursor pointer
  .treeChild
    /*display none*/
  .list_box
    > div
      border-right 1px solid #e7e7eb
      padding 10px
      width 33.3333333%
      box-sizing border-box
      display flex
      align-items center
    display flex
    flex-direction row
    width 100%
    border-bottom 1px solid #e7e7eb
    border-left 1px solid #e7e7eb
  .label-checkbox
    width 50px !important
    border-right 1px solid #e7e7eb
    >>>.el-checkbox__input
     margin 13px 0 0 17px
  .firstLevel:nth-of-type(1)
    border-top 1px solid #e7e7eb
  .call-table
    /*margin 10px 20px*/
    .lab-name
      margin-left: 10px;
      max-width: 20em;
      text-overflow: ellipsis;
      overflow: hidden;
      white-space: nowrap;
    .paddelvel2
      padding-left 21px
    .paddelvel3
      padding-left 36px
    .paddelvel4
      padding-left 51px
    .paddelvel5
     padding-left 66px
    .is_stop
      color #ff9100
    .padding-r-10
      padding-right 10px
    .operate-btn
      color $c-main
    .is_stopBtn
      color $c-pink
    .cursor
      cursor pointer
    .icon-zhankai
      cursor pointer
    .icon-zuixiaohua
      cursor pointer
    .label-input
      width: 170px
      display:inline-block
      padding-left: 5px
    .delete
      color $c-pink
      padding-left 10px
      vertical-align middle
  .label-batch
    display flex
    align-items center
    width calc(100vw - 255px)
    height 40px
    padding-left 10px
    background #fff
    position fixed
    z-index 1990
    right 0
    bottom 0
    box-shadow 1px -2px 7px rgba(0,0, 0, 0.1)
    font-size 12px
    color #595959
    > span
     margin-right 30px
     &:hover
       cursor pointer
       color $cf-gray0
       .iconfont
         color $c-main
     .iconfont
         margin-right 5px
         font-size 14px
  .call-channel-config .label-batch
     width calc(100vw - 237px)
  .navMenuState .label-batch
    width calc(100vw - 313px)
  .navMenuState .call-channel-config .label-batch
    width calc(100vw - 295px)
  .count
    position absolute
    right 18px
    b
      color $c-main
    .el-icon-close
      color $c-pink
      font-size 14px
      font-weight 700
      cursor pointer
</style>




















